// 模拟(进程池)匿名管道进程通信
#include "func.hpp"

int main()
{
    vector<pair<int, pid_t>> v;
    // int pipefd[2] = {0};
    // int n = pipe(pipefd);
    // assert(n != -1);
    for (size_t i = 0; i < 5; i++)
    {
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n != -1);
        int id = fork();
        if (id == 0)
        {
            // 子进程
            // 关闭写端
            close(pipefd[1]);
            // 使所有创建的子进程进行死循环
            while (true)
            {
                int *buf[1024] = {0};
                memset(buf,0,sizeof(1024));
                ssize_t p=read(pipefd[0], buf, sizeof(1024));
                if(p!=0)
                {
                    auto ret=m.begin();
                    ret->second();
                }
            }
        }
        // 父进程
        // 关闭读端
        close(pipefd[0]);
        // 加入数组
        v.emplace_back(make_pair(pipefd[1], id));
    }
    int choose = 0;
    while (true)
    {
        mnue();
        cin >> choose;
        if (choose < 0 || choose > 5)
            cout << "选择错误" << endl;
        else if(choose==0)
        {
            for(auto& e : v)
                close(e.first);
        }
        else
            break;
    }
    // 随机生成数字，分配给子进程
    srand((unsigned int)time(nullptr));
    int x = rand() % 5;
    // 进行写入管道
    ssize_t i=write(v[x].first, &choose, sizeof(1024));
    assert(i!=0);
    return 0;
}